package com.example.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.DTO.ShopType;
import com.example.common.Result;
import com.example.mapper.ShopTypeMapper;
import com.example.service.ShopTypeService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.example.common.RedisContants.CACHE_SHOPTYPE_LIST_KEY;

/**
 * @author chenliang
 * @description 针对表【tb_shop_type】的数据库操作Service实现
 * @createDate 2024-06-19 20:46:46
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType>
        implements ShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 店铺类型查询
     *
     * @return
     */
    @Override
    public Result queryShopType() {
        String key = CACHE_SHOPTYPE_LIST_KEY;
        //1、从redis中查询商铺缓存
        String shopTypeJson = stringRedisTemplate.opsForValue().get(key);
        //2、判断redis是否存在
        if (StrUtil.isNotBlank(shopTypeJson)) {
            //2.1、存在，直接返回——需要转成java对象返回
            List<ShopType> shopTypes = JSONUtil.toList(shopTypeJson, ShopType.class);
            return Result.ok(shopTypes);
        }

        //2.2、不存在，根据id查询数据库
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        //3、数据库中不存在，返回错误
        if (shopTypes == null) {
            return Result.fail("店铺分类不存在！");
        }
        //4、数据库中存在，写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopTypes));
        //7、返回
        return Result.ok(shopTypes);
    }

}




